package cn.ylyhappy.netdemo.support;

import androidx.annotation.NonNull;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CniaoUtils {
    /**
     * 中文转Unicode
     */
    static public String unicodeEncode(@NonNull String string) {
        char[] utfBytes = string.toCharArray();
        StringBuilder unicodeBytes = new StringBuilder();
        for (char utfByte : utfBytes) {
            String hexB = Integer.toHexString(utfByte);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes.append("\\u").append(hexB);
        }
        return unicodeBytes.toString();
    }

    /**
     * Unicode转中文
     */
    static public String unicodeDecode(@NonNull String string) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(string);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(Objects.requireNonNull(matcher.group(2)), 16);
            string = string.replace(Objects.requireNonNull(matcher.group(1)), ch + "");
        }
        return string;
    }

    /**
     * 后端暂时没有作加密，解密
     */
    public static String decodeData(@NonNull String dataStr){
        return dataStr;
    }
}
